package com.moyun.zbmy.zizhou.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.application.Cache;
import com.moyun.zbmy.zizhou.application.Constances;
import com.moyun.zbmy.zizhou.base.BaseAccountActivity;
import com.moyun.zbmy.zizhou.beans.AccountNewsItem;
import com.moyun.zbmy.zizhou.beans.AccountNewsVo;
import com.moyun.zbmy.zizhou.beans.HomeListItem;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.ui.adapter.AttentionAdapter;
import com.moyun.zbmy.zizhou.ui.util.IListShowData;
import com.moyun.zbmy.zizhou.ui.utils.DataUtils;
import com.moyun.zbmy.zizhou.utils.UserManager;
import com.ruihang.generalibrary.utils.ListUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * 互动新闻搜索
 */
public class AccountSearchNewsActivity extends BaseAccountActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, AttentionAdapter.OnAttentionNewsClickListener {
    @BindView(R.id.refreshlayout)
    protected CanRefreshLayout mRefreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;
    @BindView(R.id.input_key)
    protected EditText searchKey;
    protected static final int CODE_REQUEST_DETAIL = 112;
    private AttentionAdapter mAdapter;
    private int mPageNo = 0;
    private boolean mIsLoading = false;
    private int mPageAll = 0;
    private String keyWord;
    private HomeListItem entry = new HomeListItem();
    private List<IListShowData> dataList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_search_account_news);
        ButterKnife.bind(this);
    }

    private void initView() {
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRefreshLayout.setLoadMoreEnabled(false);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
//        mRefreshLayout.autoRefresh();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            keyWord = searchKey.getText().toString().trim();
            if (TextUtils.isEmpty(keyWord)) {
                toast("请输入关键词");
            } else {
                //TODO  搜索
                mRefreshLayout.autoRefresh();
            }
        }
        return super.dispatchKeyEvent(event);
    }


    @Override
    public void onLoadMore() {
        mPageNo++;
        search();
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        dataList.clear();
        mPageNo = 0;
        mIsLoading = true;
        search();
    }


    private void search() {
        String token = "";
        String userId = "";
        if (null != UserManager.getInstance().getUser()) {
            token = UserManager.getInstance().getUser().getToken();
            userId = UserManager.getInstance().getUser().getUserId();
        }
        Map<String, Object> param = new HashMap<>();
        param.put("siteNumber", Constances.SITE_ID);
        param.put("userId", userId);
        param.put("token", token);
        param.put("index", "" + mPageNo);
        param.put("capacity", "10");
        param.put("nodeId", Cache.getInstance().getSearchAccountNodeId());
        param.put("keyWord", keyWord);

        NetUtils.getNetAdapter().searchAccountNewsList(getOwnerName(), param, new AbsNetCallBack<AccountNewsVo>(AccountNewsVo.class) {
            @Override
            public void onSuc(AccountNewsVo listVo) {
                if (null != listVo && ListUtils.isListValued(listVo.getResultList())) {
                    dataList.addAll(listVo.getResultList());
                    mRefreshLayout.setLoadMoreEnabled(listVo.getResultList().size() >= 10 ? true : false);
                }else{
                    mRefreshLayout.setLoadMoreEnabled(false);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                if (mPageNo >= 1) {
                    mPageNo--;
                }
            }

            @Override
            public void onEnd() {
                onNetFinish();
                initData();
            }
        });
    }

    private void initData() {
        if (mAdapter == null) {
            mAdapter = new AttentionAdapter(this, dataList, this);
            mRecyclerView.setAdapter(mAdapter);
            mAdapter.setShowAuthor(true);
            mAdapter.setShowCommentLayout(false);
        } else {
            mAdapter.setData(dataList);
        }
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        mRefreshLayout.refreshComplete();
        mRefreshLayout.loadMoreComplete();
    }

    @Override
    public void OnItemClick(AccountNewsItem temp, int type) {
        if (type == AttentionAdapter.VIEWTYPE_NEWS_ITEM) {
            Intent intent = new Intent(this, AccountNewsDetailActivity.class);
            intent.putExtra(AccountNewsDetailActivity.NEWS_BEAN, temp);
            this.startActivityForResult(intent, CODE_REQUEST_DETAIL);
        } else if (type == AttentionAdapter.VIEWTYPE_NEWS_IMG_ITEM) {
            Intent intent = new Intent(this, AccountKnockOutDetailActivity.class);
            intent.putExtra(AccountKnockOutDetailActivity.NEWS_BEAN, temp);
            this.startActivityForResult(intent, CODE_REQUEST_DETAIL);
        }
    }

    @Override
    public void OnItemAccountClick(AccountNewsItem temp) {
        //TODO 进入互动账号详情
    }

    @Override
    public void OnItemCommentClick(AccountNewsItem temp, int postion) {
        //TODO 新闻评论
    }

    @Override
    public void OnItemDiggClick(AccountNewsItem temp, int postion) {
        //TODO 新闻点赞
    }

    @Override
    public void OnItemAttentionClick(AccountNewsItem temp, int postion) {
        //TODO 去关注
    }

    @OnClick({R.id.cancel})
    protected void OnClick(View v) {
        if (v.getId() == R.id.cancel) {
            finish();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CODE_REQUEST_DETAIL) {
                mRefreshLayout.autoRefresh();
            }
        }
    }
}
